package com.rabbit.common.convert;

import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * 装饰者
 *
 * @author: 顾志杰
 */
public class RabbitMessageConverter implements MessageConverter {

    private GenericMessageConverter delegate;

    /**
     * 一天
     */
    private final String delaultExprie = String.valueOf(24 * 60 * 60 * 1000);

    public RabbitMessageConverter(GenericMessageConverter genericMessageConverter){
        Preconditions.checkNotNull(genericMessageConverter);
        this.delegate = genericMessageConverter;
    }

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        /**
         * 发送消息装饰
         */
        /*过期时间一天*/
        messageProperties.setExpiration(delaultExprie);
        Message message = this.delegate.toMessage(object, messageProperties);
        return message;
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        com.rabbit.api.Message msg  = (com.rabbit.api.Message) this.delegate.fromMessage(message);
        return msg;
    }
}
